import React, {useEffect, useState} from 'react'
import { useHistory } from "react-router-dom";
import {SearchBar} from 'antd-mobile';
import '../css/search.css';
import request from "../utils/request";


export default ()=>{
    const [usearch,setusearch] = useState();
    const [ulist,setulist] = useState([])
    const history = useHistory();

    const getsearch = async ()=>{

        let ask = usearch;
        const { data } = await request.post(`/search`,{
            ask
        })
        setulist(data.data)
    }

    // useEffect(()=>{
    //     console.log('ulist',ulist)
    // },[ulist])

    //防抖
    const debounce = (fn,ms)=>{
        let timer;
        return (e)=>{
            clearInterval(timer);
            timer = setTimeout(()=>{
                fn(e);
            },ms);
        }
    }

    const OnChange = value  =>{

        setusearch(value)
    }


    useEffect(()=>{
        getsearch();
    },[usearch]);

    return (
        <section style={{width: '100%',padding:'0 5px'}}>
            <div className='search'>
                <SearchBar
                    placeholder='请输入内容'
                    showCancelButton={() => true}
                    onSearch={val => setusearch(val) }
                    onChange={debounce(OnChange,1000)}
                    style={{
                        '--border-radius': '10px',
                        '--background': '#ffffff',
                    }}
                />

            </div>
            <section style={{width: '80%',marginLeft:'10px', backgroundColor: '#fff'}}>


                    {/*&& 且运算左边为真执行右边*/}
                    {
                        ulist && ulist.map((item)=>(
                            <div className='wap' key={item._id} onClick={()=> history.push('/detail?id='+item._id)}>
                                <div className={'pic'}>
                                    <img src={item.cover}></img>
                                </div>
                                <div className={'msg'}>
                                    <span className={'title123'}>{item.title}</span>
                                    <span className={'author123'}>{item.author}</span>
                                </div>
                            </div>
                        ))
                    }

            </section>
        </section>

    )
}